package com.github.od.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.github.od.context.BaseContextHandler;
import com.github.od.util.JWTUtil;
import com.github.od.util.jwt.IJWTInfo;

/**
* JWT拦截器
* 
* @author xieweikun
* @version 2017年11月17日 下午1:48:46
*/
@Configuration
public class JWTInterceptor extends HandlerInterceptorAdapter {
	
	@Value("${jwt.token-header}")
	private String tokenHeader;
	@Autowired
	private JWTUtil jwtUtil;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求头
		String token = request.getHeader(tokenHeader);
		// 获取jwt消息
		IJWTInfo info = jwtUtil.getInfoFromToken(token);
		// 初始化全局上下文
		BaseContextHandler.setUserId(info.getId());
		BaseContextHandler.setUserName(info.getUniqueName());
		BaseContextHandler.setName(info.getName());
		
		return super.preHandle(request, response, handler);
	}

}
